from entity.evaluation import Evaluation
from log import log
from util.sqlmapper import SQLManager


class EvaluationDao:
    def setAll(self, e: Evaluation):
        with SQLManager() as db:
            db.modify("insert into t_score values (null,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)",
                      e.auc_score,
                      e.f1_score,
                      e.accuracy_score,
                      e.precision_score,
                      e.tpr,
                      e.fpr,
                      e.tnr,
                      e.fnr,
                      e.ks,
                      e.epoch,
                      e.roc_img_name,
                      e.pr_img_name,
                      e.train_id)
            log.info("insert e in db")
    def deleteByTrainId(self, train_id:int):
        with SQLManager() as db:
            db.modify("delete from t_score where train_id = %s" ,train_id)
    def getMaxAccEpochByTrainId(self, train_id: int):
        with SQLManager() as db:
            msg = db.get_one("select epoch from t_score where accuracy_score = (select max(accuracy_score) from t_score where train_id = %s) and train_id = %s",
                             (train_id,train_id)
                             )

            return msg[0]
    def getAllImgNames(self):
        with SQLManager() as db:
            msg = db.get_all("select pr_img_name,roc_img_name from t_score")
            return msg
    def getImgNamesByTrainId(self, train_id):
        with SQLManager() as db:
            msg = db.get_all("select pr_img_name,roc_img_name from t_score where train_id = %s",train_id)
            return msg
    def getByTrainId(self, train_id):
        with SQLManager() as db:
            msg_tuple = db.get_all("select * from t_score where train_id = %s", train_id)
            res = []
            for msg in msg_tuple:

                e = Evaluation()
                e.id = msg[0]
                e.auc_score = msg[1]
                e.f1_score = msg[2]
                e.accuracy_score = msg[3]
                e.precision_score = msg[4]
                e.tpr = msg[5]
                e.fpr = msg[6]
                e.tnr = msg[7]
                e.fnr = msg[8]
                e.ks = msg[9]
                e.epoch = msg[10]
                e.roc_img_name = msg[11]
                e.pr_img_name = msg[12]
                e.train_id = msg[13]
                res.append(e)
            return res

    def getMaxAccByTrainId(self, train_id):
        with SQLManager() as db:
            res = db.get_all("select accuracy_score from t_score where train_id = %s", train_id)
            if res is None or len(res) == 0 :
                return None
            return max(res)[0]